package com.xinyue.auto.sql;

import java.io.PrintWriter;
import java.util.List;

import com.xinyue.auto.bean.Attribute;
import com.xinyue.auto.bean.Entity;
import com.xinyue.auto.bean.MajorKey;
import com.xinyue.auto.sql.util.MysqlUtil;
import com.xinyue.auto.util.StringUtil;

public class MySqlDB extends SqlContext{
	/**
	 * 创建符合MySQL规范的sql语句
	 */
	@Override
	public void createSql(Entity entity, PrintWriter pw) {

		//建表语句
		pw.println("drop table if exists " + entity.getTable() + ";");
		pw.println("create table " + entity.getTable() + "(");
		
		//id
		MajorKey id = entity.getId();
		
		if(id.isAutoKey()) {
			pw.println("\t" + buildId(id) + " auto_increment,");
		}else {
			pw.println("\t" + buildId(id) + ",");
		}
		
		//Attribute
		List<Attribute> atts = entity.getAtts();
		for (Attribute att : atts) {
			//是数据库字段
			if(att.isDbField()) {
				pw.println("\t" + buildField(att) + ",");
			}
		}
		
		//主键和结尾
		pw.println("\t" + "primary key(" + id.getDbName() + ")");
		
		if(StringUtil.isNull(id.getStart())) {
			pw.println(");");
		}else {
			pw.println(")AUTO_INCREMENT=" + id.getStart() + ";");
		}
		pw.println();
	}
	
	
	/**
	 * 构建符合mySql规范的sql语句
	 * @return
	 */
	private String buildId(MajorKey id) {
		return MysqlUtil.buildSql(id.getDbName(), id.getType(), id.getLength(), true, false);
	}
	
	/**
	 * 构建符合mySql规范的sql语句
	 * @return
	 */
	private String buildField(Attribute att) {
		return MysqlUtil.buildSql(att.getDbName(), att.getDbType(), att.getLength(), att.isNullable(), att.isUnique());
	}
}
